package com.example.universitylibraryback.service.impl;

import com.example.universitylibraryback.pipeline.Pipeline;
import com.example.universitylibraryback.pipeline.BorrowContext;
import com.example.universitylibraryback.pipeline.filter.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * 借阅流程服务，集成管道和服务
 */
@Service
public class BorrowProcessService {
    
    @Autowired
    private BorrowRequestParserFilter borrowRequestParserFilter;
    
    @Autowired
    private ValidationFilter validationFilter;
    
    @Autowired
    private ReaderQualificationFilter readerQualificationFilter;
    
    @Autowired
    private BookStatusFilter bookStatusFilter;
    
    @Autowired
    private BorrowRecordCreationFilter borrowRecordCreationFilter;
    
    @Autowired
    private BookStatusUpdateFilter bookStatusUpdateFilter;
    
    public boolean processBorrowRequest(String readerId, String bookId, String operatorRole) {
        try {
            // 创建管道并组装过滤器
            Pipeline<BorrowContext> pipeline = new Pipeline<>();
            pipeline.addFilter(borrowRequestParserFilter)
                    .addFilter(validationFilter)
                    .addFilter(readerQualificationFilter)
                    .addFilter(bookStatusFilter)
                    .addFilter(borrowRecordCreationFilter)
                    .addFilter(bookStatusUpdateFilter);

            // 创建上下文对象并提交到管道处理
            String requestData = readerId + "," + bookId;
            BorrowContext context = new BorrowContext(requestData);
            pipeline.submit(context);

            // 等待处理完成
            TimeUnit.SECONDS.sleep(1);

            // 关闭管道
            pipeline.shutdown();
            
            // 返回处理结果
            return context.isValid();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
}